<?php


namespace app\admin\business;


use think\Exception;

class AdminUser
{
    protected $adminUserObj = null;
    public function __construct()
    {
        $this->adminUserObj = new \app\admin\model\mysql\AdminUser();
    }

    /**
     * 账号登录 验证信息
     * @param $data
     * @return bool
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login($data) {
        $user = $this->getAdminUserByUsername($data);
        if (!$user) {
            throw new Exception('账号或密码不正确01');
        }
        //验证密码
        //验证密码  md5(password + 'zihou')
        if (md5($data['password'] . $user['pwd_salt']) !== $user['password']) {
            throw new Exception('账号或密码不正确02');
        }
        //更新登录信息
        $updateData = [
            'last_login_time' => time(),
            'last_login_ip' => request()->ip(),
        ];
        $res = $this->adminUserObj->updateById($user['id'], $updateData);
        if (empty($res)) {
            throw new Exception('内部异常， 登录失败');
        }

        //记录session
        session(config('admin.session_admin'), $user);
        return true;
    }

    /**
     * 根据用户名获取用户信息
     * @param $data
     * @return array|bool|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAdminUserByUsername($data) {
        $adminUser = $this->adminUserObj->getAdminUserByUsername($data['username']);
        if (empty($adminUser)) {
            return [];
        }
        $adminUser = $adminUser->toArray();
        return $adminUser;
    }

}